home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 986 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.2 KB  |  57 lines

  1. Path: fido.asd.sgi.com!austern
  2. From: vavasis@CS.Cornell.EDU (Stephen Vavasis)
  3. Newsgroups: comp.std.c++
  4. Subject: C++ syntactic trap
  5. Date: 06 Apr 1996 11:33:39 PST
  6. Organization: Cornell Univ. CS Dept, Ithaca NY 14853
  7. Approved: austern@isolde.mti.sgi.com
  8. Message-ID: <4k3q4p$lkd@syn.cs.cornell.edu>
  9. NNTP-Posting-Host: isolde.mti.sgi.com
  10. X-Original-Date: 5 Apr 1996 13:52:09 -0500
  11. X-Auth: PGPMoose V1.1 PGP comp.std.c++
  12.     iQBVAwUBMWbHFEy4NqrwXLNJAQFpQAH+Lo5yP9Gurz7LTLklIIxiMghHtU2JKM18
  13.     M/+dh2agzyzLQQnOzAtH/NRsc3xmUFWdfXSt3SGEp+XNLoLizqBz/g==
  14.     =yNcj
  15. Originator: austern@isolde.mti.sgi.com
  16.  
  17. I have just spent a long time tracking down a mysterious bug (the
  18. heap-trashing variety of bug) in my program caused by a syntactic trap
  19. in C++.  The troubling thing about this trap is that none of the unix
  20. compilers I tried (gcc-2.7.2, Sun SC3.0.1, HP-UX cfront 3.0.3) issued
  21. a warning about the mistake, even on the highest warning level.  Only
  22. Visual C++4.0 observed that there might be a problem.  Here is an
  23. example of the trap.  This program asks the user how many asterisks,
  24. and then prints out that many asterisks.
  25.  
  26. #include <iostream.h>
  27. int main() {
  28.   cout << " How many *'s? ";
  29.   int sz; cin >> sz;
  30.   char* a = new char(sz + 1); // bug is here, but syntax is legal.
  31.   for (int i = 0; i < sz; i++)
  32.     a[i] = '*';
  33.   a[sz] = 0;
  34.   cout << a << endl;
  35.   delete[] a;
  36.   return 0;
  37. }
  38.  
  39. (Does everyone see the error?  I did not, even after staring at my
  40. code for a long time.  The point is that the marked statement is an
  41. unintended cast from int to char because I used () instead of [].)
  42.  
  43. I would like to make a plea to the compiler-writers who read this
  44. group: please issue warnings for syntactic trouble spots!  Implicit
  45. type conversion probably creates other traps that I haven't thought
  46. of.  C++ programmers like me need help from the compiler to navigate
  47. the traps!
  48.  
  49. -- Steve Vavasis (vavasis@cs.cornell.edu)
  50. ---
  51. [ comp.std.c++ is moderated.  To submit articles: Try just posting with your 
  52.                 newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  53.   comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  54.   Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  55.   Comments? mailto:std-c++-request@ncar.ucar.edu 
  56. ]
  57.